package com.interview.service.impl;

import com.interview.entity.User;
import com.interview.entity.param.LoginParam;
import com.interview.mapper.UserMapper;
import com.interview.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author JiangYingbo
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(LoginParam loginParam) {
        // 组装用户登录条件
        User condition = new User();
        condition.setUsername(loginParam.getUsername());
        condition.setPassword(loginParam.getPassword());

        // 根据条件查询用户
        List<User> users = userMapper.select(condition);
        if (users.isEmpty()) {
            throw new RuntimeException("账号或密码错误！");
        }
        return users.get(0);
    }

    @Override
    public User userInfo(Integer userId) {
        // 组装用户查询条件
        User condition = new User();
        condition.setUserId(userId);
        return userMapper.select(condition).get(0);
    }

    @Override
    public void register(User user) {
        User condition = new User();
        // 验证手机号
        condition.setPhone(user.getPhone());
        if (!userMapper.select(condition).isEmpty()) {
            throw new RuntimeException("手机号已注册！");
        }
        // 验证用户名
        condition.setPhone(null);
        condition.setUsername(user.getUsername());
        if (!userMapper.select(condition).isEmpty()) {
            throw new RuntimeException("用户名已注册！");
        }
        // 验证邮箱
        condition.setUsername(null);
        condition.setEmail(user.getEmail());
        if (!userMapper.select(condition).isEmpty()) {
            throw new RuntimeException("邮箱已注册！");
        }
        // 设置默认头像
        user.setAvatarUrl("default.jpg");
        // 保存用户
        int res = userMapper.insert(user);
        if (res <= 0) {
            throw new RuntimeException("注册失败！");
        }
    }

    @Override
    public int updateUserInfo(User user) {
        int res = userMapper.update(user);
        if (res <= 0) {
            throw new RuntimeException("更新失败！");
        }
        return res;
    }
}
